var express = require('express');
var router = express.Router();
var appConfig = require('../appConfig');
var getWxuserInfo = require('../src/getWxuserInfo');
var getWbuserInfo = require('../src/getWbuserInfo');
var getQqInfo = require('../src/getQqInfo');

var getResponseObj = function (openid,nickname,headimgurl) {
    var obj = new Object();
    obj['openid'] = openid ;
    obj['nickname'] = nickname ;
    obj['head_img'] = headimgurl ;
    return obj;
}
/* GET home page. */
router.get('/index', function(req, res, next) {
    var source = req.query.source;
    var configObj = source == 'wx' ? appConfig.wxconfig :
        (source == 'sina' ? appConfig.sinaconfig : appConfig.qqconfig)
    res.render('index', { title: 'Express',appid:configObj.appid } );
});

router.get('/work', function(req, res, next) {
    res.render('work', { title: 'Express'} );
});

router.get('/theme', function(req, res, next) {
    res.render('theme', { title: '精选专题'} );
});

router.get('/download', function(req, res, next) {
    res.render('download', { title: 'Express'} );
});

router.get('/work/Wechat', function(req, res, next) {
    var code = req.query.code;
    getWxuserInfo(code).then(response=>{
        var BuserData =  getResponseObj(response.openid,response.nickname,response.headimgurl)
        res.json({ code:1,data:BuserData,msg:'获取成功'});
    }).catch(err=>{
        res.json({code:-1,msg:err});
    })
});

router.get('/work/SinaWeibo', function(req, res, next) {
    var code = req.query.code;
    getWbuserInfo(code).then(response=>{
        var data = JSON.parse(response);
        var BuserData = getResponseObj(data.id,data.name,data.avatar_large )
        res.json({ code:1,data:BuserData,msg:'获取成功'});
    }).catch(err=>{
        res.json({code:-1,msg:err});
    })
});

router.get('/work/QQ', function(req, res, next) {
    var code = req.query.code;
    getQqInfo(code).then(response=>{
        res.json({ code:1,data:response,msg:'获取成功'});
    }).catch(err=>{
        res.json({code:-1,msg:err});
    })
});

module.exports = router;
